package github.leavesczy.reactivehttpsamples

import android.os.Bundle
import androidx.fragment.app.Fragment
import github.leavesczy.reactivehttpsamples.adapter.MainTabAdapter
import github.leavesczy.reactivehttpsamples.base.BaseActivity
import github.leavesczy.reactivehttpsamples.databinding.ActivityMain2Binding
import github.leavesczy.reactivehttpsamples.ui.main.HistoryFragment
import github.leavesczy.reactivehttpsamples.ui.main.HomeFragment
import github.leavesczy.reactivehttpsamples.util.Logger
import github.leavesczy.reactivehttpsamples.widget.maintab.TabItem

class Main2Activity : BaseActivity() {

    private val fragmentList = mutableListOf<Fragment>()

    override val bind by getBind<ActivityMain2Binding>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initTabs()
        initFragment()
        initViewPage()
    }


    fun initTabs() {
        val items = mutableListOf<TabItem>()
        Tab.values().forEach { tab ->
            val item = TabItem()
            item.type=TabItem.Type.TEXT
            item.id = tab.index
            item.drawable = tabImageRes.get(tab.resIndex)
            item.text=tab.tabName
            item.color=tabTextColorRes[tab.resIndex]
            items.add(item)
        }
        bind.mainTabGroup.initView(items) { view, item ->
            //tab点击时间
            val currentIndex = bind.mainViewPage.currentItem
            Logger.d("切换tab:"+item.id+" ;current:"+currentIndex)
            if (currentIndex == item.id) {
                return@initView
            }
            //切换tab
            bind.mainViewPage.setCurrentItem(item.id,false)
        }
    }

    fun initFragment() {
        fragmentList.clear()

        fragmentList.add(HomeFragment.newInstance())
        fragmentList.add(HistoryFragment.newInstance())

    }

    fun initViewPage() {
        val adapter = MainTabAdapter(supportFragmentManager, lifecycle)
        adapter.setFragments(fragmentList)

        bind.mainViewPage.adapter = adapter
        //禁止左右滑动
        bind.mainViewPage.isUserInputEnabled=false
        bind.mainViewPage.setCurrentItem(0,false)
        bind.mainTabGroup.setSelected(Tab.HOME.index)

    }


    /**
     * tabs 的图片资源
     */
    private val tabImageRes = intArrayOf(
        R.drawable.main_tab_home,
        R.drawable.main_tab_learn
    )

    private val tabTextColorRes= intArrayOf(
        R.drawable.main_tab_text,
        R.drawable.main_tab_text
    )

    enum class Tab(val resIndex: Int, val index: Int,val tabName:String) {
        HOME(0, 0,"首页"), HISTORY(1, 1,"桥梁档案")
    }
}